<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => '用户未登录']);
    exit();
}

require 'config.php';

$user_id = $_SESSION['user_id'];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $post_id = $_POST['post_id'];
    $action = $_POST['action'];

    if ($action == 'like') {
        // 检查用户是否已经点赞
        $check_like_stmt = $conn->prepare("SELECT id FROM likes WHERE user_id = ? AND post_id = ?");
        $check_like_stmt->bind_param("ii", $user_id, $post_id);
        $check_like_stmt->execute();
        $check_like_stmt->store_result();

        if ($check_like_stmt->num_rows == 0) {
            // 插入点赞记录
            $like_stmt = $conn->prepare("INSERT INTO likes (user_id, post_id) VALUES (?, ?)");
            $like_stmt->bind_param("ii", $user_id, $post_id);
            $like_stmt->execute();
            $like_stmt->close();
        }

        $check_like_stmt->close();
    } elseif ($action == 'unlike') {
        // 删除点赞记录
        $unlike_stmt = $conn->prepare("DELETE FROM likes WHERE user_id = ? AND post_id = ?");
        $unlike_stmt->bind_param("ii", $user_id, $post_id);
        $unlike_stmt->execute();
        $unlike_stmt->close();
    }

    // 获取最新的点赞数量
    $like_count_stmt = $conn->prepare("SELECT COUNT(*) FROM likes WHERE post_id = ?");
    $like_count_stmt->bind_param("i", $post_id);
    $like_count_stmt->execute();
    $like_count_stmt->bind_result($like_count);
    $like_count_stmt->fetch();
    $like_count_stmt->close();

    echo json_encode(['status' => 'success', 'like_count' => $like_count]);
    exit();
}
?>